package test1

import (
	"fmt"
	"net/http"
	"strconv"
	"sync"
	"websocket/melody"

	"github.com/gin-gonic/gin"
)

type Test1 struct {
	ws   *melody.Melody
	sess map[int64]*Session1
	sync.RWMutex
}

func New() *Test1 {
	t := &Test1{
		ws:   melody.New(),
		sess: make(map[int64]*Session1),
	}
	t.initHandler()
	return t
}

func (t *Test1) initHandler() {
	t.ws.RegisterHandler(t)
}
func (t *Test1) Handler(w http.ResponseWriter, r *http.Request, c *gin.Context) error {
	s, err := t.ws.Connect(w, r)
	if err != nil {
		return err
	}
	userId := c.Param("userId")
	uid, _ := strconv.ParseInt(userId, 10, 64)
	s1 := NewSession1(s, uid)
	t.sess[uid] = s1
	return t.ws.Server(s1, s)
}
func (t *Test1) HandlerMessage(ss interface{}, msg []byte) {
	s := ss.(*Session1)
	fmt.Println(s.Uid(), string(msg))
	s.Write(msg)
}
func (t *Test1) HandlerSend(interface{}, []byte) {}
func (t *Test1) Error(ss interface{}, err error) {
	s := ss.(*Session1)
	uid := s.Uid()
	fmt.Println("Error close session the uid is:", uid, err)
	t.delSess(uid)
}
func (t *Test1) Close(ss interface{}, id int, text string) error {
	s := ss.(*Session1)
	uid := s.Uid()
	t.delSess(uid)
	fmt.Println("Close close session the uid is:", uid, id, text)

	return nil
}
func (t *Test1) Connect(s *melody.Session) {
}
func (t *Test1) DisConnect(ss interface{}) {
	s := ss.(*Session1)
	uid := s.Uid()
	fmt.Println("DisConnect close session the uid is:", uid)
	t.delSess(uid)
}
func (t *Test1) HandlerPong(interface{}) {}

func (t *Test1) delSess(uid int64) {
	t.RLock()
	defer t.RUnlock()
	_, ok := t.sess[uid]
	if ok {
		delete(t.sess, uid)
	}
}
